import 'package:flutter/material.dart';

import '../common/api/work_order_api.dart';
import '../common/const/app_color_const.dart';
import '../common/const/app_style_const.dart';
import '../common/enum/btn_enum.dart';
import '../common/enum/work_order_detail_enum.dart';
import '../common/util/common_util.dart';
import '../widget/card_container.dart';
import '../widget/empty.dart';
import '../widget/error_img.dart';
import '../widget/form_item.dart';
import '../widget/icon_outlined_btn.dart';
import '../widget/ripple_card_container.dart';
import '../widget/user_picker.dart';

class WorkOrderDetail extends StatefulWidget {
  final String no;
  final DetailType detailType;

  const WorkOrderDetail({Key? key, required this.no, required this.detailType})
      : super(key: key);

  @override
  State<WorkOrderDetail> createState() => WorkOrderDetailState();
}

class WorkOrderDetailState extends State<WorkOrderDetail> {
  Map? data;
  List<dynamic> dataList = [];
  bool isCheckUpSampleGoods = false;

  @override
  void initState() {
    super.initState();
    initData();
  }

  initData() {
    WorkOrderApi.getOrderDetail({"workOrderNo": widget.no}).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        data = res.data["data"];
        setState(() {});
        initOrderGoodsSampleList();
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  initOrderGoodsSampleList() {
    WorkOrderApi.getOrderGoodsSampleList({"workOrderNo": widget.no})
        .then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        dataList = res.data["data"];
        dataList = [
          {
            "picUrl": "",
            "resParameList": [
              {
                "parameName": "款式",
                "parameValue":
                    "红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包红包",
              },
              {
                "parameName": "朝秦暮楚 地",
                "parameValue": "红包红包红包红包红包红包红包红包红包红包",
              }
            ]
          },
          {
            "picUrl": "",
            "resParameList": [
              {
                "parameName": "颜色",
                "parameValue": "红色",
              },
              {
                "parameName": "大小",
                "parameValue": "S码",
              },
              {
                "parameName": "材质",
                "parameValue": "棉布",
              },
              {
                "parameName": "标准",
                "parameValue": "国标IOS-8859-002",
              }
            ]
          }
        ];
        setState(() {});
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  adminReview() {}

  checkUpSampleGoods() {}

  startCheckUpSampleGoods() {}

  staffProcess() {}

  staffSubReview() {}

  Future assign() {
    return showModalBottomSheet(
      context: context,
      builder: (ctx) {
        return UserPicker(
            queryParams: {
              "page": 1,
              "limit": 99999999,
              "liveLocId": data!["liveLocId"] ?? ""
            },
            labelBuilder: (ctx, user, labelStyle) => Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(user['userName'], style: labelStyle),
                    Text(
                        '工单数：${user['ingWorkOrderNum'] > 999 ? '999+' : user['ingWorkOrderNum']}',
                        style: labelStyle)
                  ],
                ),
            onChecked: (res) {
              if (res.employeeNum.isEmpty) {
                CommonUtil.showToast("请选员工！");
                return false;
              }
              return true;
            },
            onResult: (res) {
              WorkOrderApi.updateAssignStaffUer(
                      {"staffAccountId": res.id, "workOrderNo": widget.no})
                  .then((res) {
                if (null != res.data && res.data["isSuccess"]) {
                  initData();
                } else {
                  CommonUtil.showToast(res.data["msg"]);
                }
              });
            });
      },
    );
  }

  prepareLocRoomComplete() {}

  verifyLiveUserSignIn() {}

  workOrderDetailBaseInfoBodyBuilder(context) {
    if (null != data) {
      return Container(
        color: lightGrayColor8,
        padding: const EdgeInsets.all(8.0),
        child: Column(children: [
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '工单号',
              valueWidth: constraints.maxWidth - 60,
              value: CommonUtil.valueEmptyToDefStr(data!['workOrderNo']),
            );
          }),
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '房间号',
              valueWidth: constraints.maxWidth - 60,
              value: CommonUtil.valueEmptyToDefStr(data!['liveRoomNo']),
            );
          }),
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '预定日期',
              valueWidth: constraints.maxWidth - 70,
              value: CommonUtil.valueEmptyToDefStr(data!['bookDt']),
            );
          }),
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '预定时段',
              valueWidth: constraints.maxWidth - 70,
              value:
                  '${CommonUtil.valueEmptyToDefStr(data!['bookStartTime'])} - ${CommonUtil.valueEmptyToDefStr(data!['bookEndTime'])}',
            );
          }),
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '预约人',
              valueWidth: constraints.maxWidth - 60,
              value: CommonUtil.valueEmptyToDefStr(data!['bookUserName']),
            );
          }),
          LayoutBuilder(builder: (buildContext, constraints) {
            return FormItem(
              label: '联系方式',
              valueWidth: constraints.maxWidth - 70,
              value: CommonUtil.valueEmptyToDefStr(data!['contactTel']),
            );
          }),
        ]),
      );
    } else {
      return const Padding(
        padding: EdgeInsets.only(top: 10.0),
        child: Empty(),
      );
    }
  }

  sampleGoodsParamListBuild(List list) {
    List<Widget> sampleGoodsParamList = [];
    for (var item in list) {
      sampleGoodsParamList
          .add(LayoutBuilder(builder: (buildContext, constraints) {
        return FormItem(
          label: item['parameName'] ?? '',
          valueWidth: constraints.maxWidth - 70,
          labelWidth: 70,
          labelTextAlign: TextAlign.right,
          valuePadding: const EdgeInsets.only(left: 8),
          value: CommonUtil.valueEmptyToDefStr(item['parameValue'] ?? ''),
        );
      }));
    }
    return sampleGoodsParamList;
  }

  workOrderDetailSampleGoodsInfoBodyBuilder(context) {
    if (dataList.isNotEmpty) {
      return Column(
        children: List.generate(
            dataList.length,
            (index) => Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Container(
                    color: lightGrayColor8,
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            RippleCardContainer(
                                width: 60,
                                height: 50,
                                onTap: () {
                                  CommonUtil.showImgViewer(
                                      context, 0, [dataList[index]['picUrl']]);
                                },
                                child: dataList[index]['picUrl'].isNotEmpty
                                    ? Image.network(
                                        dataList[index]['picUrl'],
                                        errorBuilder: (BuildContext context,
                                                Object error,
                                                StackTrace? stackTrace) =>
                                            const ErrorImg(),
                                      )
                                    : const ErrorImg()),
                            Expanded(
                                child: Padding(
                                    padding: const EdgeInsets.only(left: 10.0),
                                    child: Column(
                                        children: sampleGoodsParamListBuild(
                                            dataList[index]['resParameList']))))
                          ],
                        ),
                        if (null != data && data!['workOrderStatus'] >= 8)
                          Padding(
                            padding: const EdgeInsets.only(top: 10.0),
                            child: Container(
                              decoration: BoxDecoration(
                                color: whiteColor,
                                border:
                                    const Border.fromBorderSide(borderStyle),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              child: Row(
                                children: [
                                  Flexible(
                                    child: RadioListTile(
                                      dense: true,
                                      enableFeedback: false,
                                      visualDensity:
                                          const VisualDensity(horizontal: -3.5),
                                      title: const Text('正常'),
                                      contentPadding: const EdgeInsets.all(0),
                                      onChanged: (value) {
                                        if (isCheckUpSampleGoods) {
                                          setState(() {
                                            dataList[index]['checkStatus'] =
                                                value;
                                          });
                                        }
                                      },
                                      groupValue: dataList[index]
                                          ['checkStatus'],
                                      value: 1,
                                    ),
                                  ),
                                  Flexible(
                                    child: RadioListTile(
                                      activeColor: orangeColor,
                                      dense: true,
                                      visualDensity:
                                          const VisualDensity(horizontal: -3.5),
                                      title: const Text('破损'),
                                      contentPadding: const EdgeInsets.all(0),
                                      onChanged: (value) {
                                        if (isCheckUpSampleGoods) {
                                          setState(() {
                                            dataList[index]['checkStatus'] =
                                                value;
                                          });
                                        }
                                      },
                                      groupValue: dataList[index]
                                          ['checkStatus'],
                                      value: 2,
                                    ),
                                  ),
                                  Flexible(
                                    child: RadioListTile(
                                      activeColor: redColor,
                                      dense: true,
                                      visualDensity:
                                          const VisualDensity(horizontal: -3.5),
                                      title: const Text('丢失'),
                                      contentPadding: const EdgeInsets.all(0),
                                      onChanged: (value) {
                                        if (isCheckUpSampleGoods) {
                                          setState(() {
                                            dataList[index]['checkStatus'] =
                                                value;
                                          });
                                        }
                                      },
                                      groupValue: dataList[index]
                                          ['checkStatus'],
                                      value: 3,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          )
                      ],
                    ),
                  ),
                )),
      );
    } else {
      return const Padding(
        padding: EdgeInsets.only(top: 10.0),
        child: Empty(),
      );
    }
  }

  buildOperationBtnList() {
    List<Widget> btnList = [];

    if (widget.detailType == DetailType.assignWorkOrder) {
      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["assignBtn"] &&
              true == data!["handleOption"]["assignBtn"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '指派',
                btnType: BtnType.primary,
                onPressed: () {
                  assign();
                }),
          ),
        ));
      }
    }

    if (widget.detailType == DetailType.workAudit) {
      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["adminReviewBtn"] &&
              true == data!["handleOption"]["adminReviewBtn"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '通过',
                btnType: BtnType.green,
                onPressed: () {
                  adminReview();
                }),
          ),
        ));
      }

      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["checkUpSampleGoods"] &&
              true == data!["handleOption"]["checkUpSampleGoods"])) {
        isCheckUpSampleGoods = true;

        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '提交清点结果',
                btnType: BtnType.green,
                onPressed: () {
                  checkUpSampleGoods();
                }),
          ),
        ));
      }
    }

    if (widget.detailType == DetailType.stockOrder) {
      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["prepareLocRoomComplete"] &&
              true == data!["handleOption"]["prepareLocRoomComplete"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '备场完成',
                btnType: BtnType.green,
                onPressed: () {
                  prepareLocRoomComplete();
                }),
          ),
        ));
      }

      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["staffProcessBtn"] &&
              true == data!["handleOption"]["staffProcessBtn"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '开始处理',
                btnType: BtnType.primary,
                onPressed: () {
                  staffProcess();
                }),
          ),
        ));
      }

      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["staffSubReviewBtn"] &&
              true == data!["handleOption"]["staffSubReviewBtn"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '提交审核',
                btnType: BtnType.green,
                onPressed: () {
                  staffSubReview();
                }),
          ),
        ));
      }

      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["verifyLiveUserSignin"] &&
              true == data!["handleOption"]["verifyLiveUserSignin"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '核实主播到场',
                btnType: BtnType.primary,
                onPressed: () {
                  verifyLiveUserSignIn();
                }),
          ),
        ));
      }

      if (null != data &&
          null != data!["handleOption"] &&
          (null != data!["handleOption"]["startcheckUpSampleGoodsBtn"] &&
              true == data!["handleOption"]["startcheckUpSampleGoodsBtn"])) {
        btnList.add(Expanded(
          child: Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: IconOutlinedBtn(
                text: '发起直播间清点',
                btnType: BtnType.primary,
                onPressed: () {
                  startCheckUpSampleGoods();
                }),
          ),
        ));
      }
    }

    if (btnList.isEmpty) {
      return Container();
    }

    return Container(
        padding: const EdgeInsets.only(left: 7, right: 7, bottom: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: btnList,
        ));
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        controller: ScrollController(),
        child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: CardContainer(
                bodyPadding: const EdgeInsets.all(0.0),
                bodyBuilder: (context) => Column(
                      children: [
                        CardContainer(
                            title: '详情信息',
                            decorationVisible: false,
                            bodyBuilder: (context) =>
                                workOrderDetailBaseInfoBodyBuilder(context)),
                        CardContainer(
                            title: '样衣列表',
                            decorationVisible: false,
                            bodyBuilder: (context) =>
                                workOrderDetailSampleGoodsInfoBodyBuilder(
                                    context)),
                        buildOperationBtnList()
                      ],
                    ))));
  }
}
